package com.ddm.service.impl.vxImpl;



import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ddm.constant.MessageConstant;
import com.ddm.dto.page.PageQueryDTO;
import com.ddm.dto.vxDTO.LoginDTO;
import com.ddm.dto.vxDTO.UserDTO;
import com.ddm.dto.vxDTO.WechatPhoneLoginDTO;
import com.ddm.entity.vxEntity.User;
import com.ddm.exception.DataErrorException;
import com.ddm.exception.LoginFailedException;
import com.ddm.mapper.ScoreMapper;
import com.ddm.mapper.UserMapper;
import com.ddm.properties.JwtProperties;
import com.ddm.properties.OpenProperties;
import com.ddm.result.PageResult;
import com.ddm.service.vxService.UserService;
import com.ddm.service.vxService.WechatApiService;
import com.ddm.utils.BeanCopyUtil;
import com.ddm.vo.vxVo.UserVo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author horizon
 * @since 2025-01-17
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserService userService;
    @Autowired
    OpenProperties openProperties;
    @Autowired
    JwtProperties jwtProperties;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ScoreMapper scoreMapper;
    @Autowired
    WechatApiService wechatApiService;
    // 其他已有方法...
    @Autowired
    private WxMaService wxMaService;

    /**
     * 分页查询用户
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult getUserList(PageQueryDTO pageQueryDTO) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            Page<User> userPage = new Page(pageQueryDTO.getPage() , pageQueryDTO.getPageSize());
            queryWrapper.orderByAsc(User::getCreateTime);
            List<User> records = userService.page(userPage, queryWrapper).getRecords();
            long total = userPage.getTotal();
            List<UserVo> userListVos = BeanCopyUtil.BeanCopyList(records, UserVo.class);
            return new PageResult(total,userListVos);
    }

    /**
     * 微信登录
     * @param loginDTO
     * @return
     */
    @Override
    public User vxLogin(LoginDTO loginDTO) {

        //获得openId
        String openid = getOpenId(loginDTO.getCode());

        if (openid ==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //根据openid判断用户是否为第一次登录
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getOpenid , openid);
        User exitUser = userMapper.selectOne(wrapper);
        if (exitUser == null){
            //创建新用户
           exitUser =  User.builder()
                        .openid(openid)
                        .userName(loginDTO.getName())
                        .photoUrl(loginDTO.getImage())
                        .userType(0)
                   //给前端页面密码
                   .password(loginDTO.getCode())
                        .createTime(LocalDateTime.now())
                        .build();
           userService.save(exitUser);
        }

        return exitUser;
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public UserVo getByid(Long id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId , id);
        User user = userService.getOne(wrapper);
        if (user ==null){
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }
        UserVo userVo = BeanCopyUtil.BeanCopy(user, UserVo.class);
        return userVo;
    }

    /**
     * 根据id查询用户类型
     * @param id
     * @return
     */
    @Override
    public Integer getUserTypeById(Long id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getId , id);
        User user = userService.getOne(wrapper);
        if (user ==null){
            throw new DataErrorException(MessageConstant.ERROR_DATA);
        }
        Integer userType = user.getUserType();
        return userType;
    }
    @Override
    public void deleteUserList(List<UserDTO> userDTOS) {
        Long userId = null;
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        ArrayList<User> list = new ArrayList<>();
        List<Long> userIds = userDTOS.stream().map(UserDTO::getUserId).collect(Collectors.toList());
        for (UserDTO userDTO : userDTOS) {
            userId = userDTO.getUserId();
            wrapper.eq(User::getId,userId);
            User user = userMapper.selectOne(wrapper);
            if (user == null){
                throw new DataErrorException(MessageConstant.ERROR_DATA);
            }
            list.add(user);
        }
        userMapper.deleteBatchIds(list);
    }



    public String getOpenId(String code){
        //code + 小程序id + 小程序密钥 请求微信接口服务
        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");

        String tokenUrl = String.format(url.toString(),
                openProperties.getAppId(),
                openProperties.getAppSecret(),
                code
        );
        String body = null;
        String session_key = null;
        String openid = null ;
        try {
            //发送请求
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(tokenUrl).build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()){
                body = response.body().string();
                JSONObject jsonObject = JSONObject.parseObject(body);
                session_key = jsonObject.getString("session_key");
                openid = jsonObject.getString("openid");
            }
        } catch (IOException e) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        return openid;
    }




//
////查询是否有这个手机号码记录
//    @Override
//    public User findUserByPhoneNumber(String phoneNumber) {
//        List<User> users = new ArrayList<>();
//        return users.stream()
//                .filter(user -> user.getPhoneNum().equals(phoneNumber))
//                .findFirst()
//                .orElse(null);
//    }
@Override
public User loginByPhoneNumber(WechatPhoneLoginDTO loginDTO) {
    try {
        // 1. 调用微信接口获取手机号,openId
        String phoneNumber = wechatApiService.getPhoneNumberByCode(loginDTO.getPhoneCode());
        String openid=loginDTO.getOpenid();
        if (StringUtils.isEmpty(phoneNumber)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED1);
        }
        if (StringUtils.isEmpty(openid)) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED2);
        }

//        // 2. 查询手机号对应的用户
//        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(User::getPhoneNum, phoneNumber);
//        User existUser = userMapper.selectOne(queryWrapper);


//        2. 查询openid应的用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, openid);
        User existUser = userMapper.selectOne(queryWrapper);

//        // 3. 已存在则返回（可关联openid）
//        if (existUser != null) {
//            // 若前端传递了phoneNum，更新用户的openid（绑定微信账号）
//            if (StringUtils.isNotEmpty(loginDTO.getOpenid())) {
//                existUser.setOpenid(loginDTO.getOpenid());
//                userMapper.updateById(existUser);
//            }
//            return existUser;
//        }


        // 3. 已存在则返回
        if (existUser != null) {
            // 若前端传递了phoneNum，更新用户的phoneNum（绑定微信账号）
            if (StringUtils.isNotEmpty(phoneNumber)) {
                existUser.setPhoneNum(phoneNumber);
                userMapper.updateById(existUser);
            }
            return existUser;
        }
        // 4. 不存在则创建新用户
        User newUser = User.builder()
                .phoneNum(phoneNumber)
                .openid(loginDTO.getOpenid()) // 关联openid（可选）
                .userName(loginDTO.getUserName() != null ? loginDTO.getUserName() : "用户_" + phoneNumber.substring(7))
                .photoUrl(loginDTO.getPhotoUrl())
                .userType(0)
                .password(loginDTO.getPhoneCode())
                .createTime(LocalDateTime.now())
                .build();
        userMapper.insert(newUser);
        return newUser;

    } catch (Exception e) {
        log.error("微信手机号登录失败", e);
        throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
    }
}
}
